// 用户管理,锁具设置错误码处理
export function handleStartErr(Err) {
	let pages = getCurrentPages();
	let targetIndex = -1;
	let currentIndex = pages.length - 1;
	let targetPath = uni.getStorageSync('startErrToPath') || 'jvss/pages/device/home'
	pages.forEach((item, index) => {
		if (item.route == targetPath) {
			targetIndex = index;
		}
	})
	let delta = currentIndex - targetIndex;
	console.log(Err, delta, pages, currentIndex, pages.length)
	uni.showModal({
		title: '提示',
		confirmText: '确认',
		confirmColor: '#1AC0BA',
		showCancel: false,
		content: '长时间未操作，退出设置',
		success: (res) => {
			uni.navigateBack({
				delta: delta
			})
		},
	});
}

// 十进制转16进制0x开头字符串
export const turnTenToSixteen = (ten) => {
	let origin = '0x' + Number(ten).toString(16)
	let end = origin
	if (origin.length === 3) {
		let arr = origin.split('')
		arr.splice(2, 0, '0')
		end = arr.join('')
	}
	return end
}

// 用户管理 锁具设置操作数据处理
export function handledoorLockTransparent(result, callback, simple = false, callbackError, type = 'DoorUser') {
	result = result.data;
	if (result.code == 2000) {
		if (result.data.Ret == 100) {
			let Err = turnTenToSixteen(result.data[type].Err)
			console.log('Err=====>', Err)
			if (Err == '0x14') {
				handleStartErr(Err)
			} else {
				if (simple) {
					if (typeof callback == 'function') {
						callback(result.data[type], Err)
					}
				} else {
					if (Err == '0x00') {
						if (typeof callback == 'function') {
							callback(result.data[type], Err)
						}
					} else {
						uni.showToast({
							title: getApp().globalData.errCodeMsg.wakeUpLockBoardCodeMsg[Err] || result.data
								.msg,
							icon: 'none',
							duration: 2000
						});
					}
				}
				// callback
			}
		} else if (result.data.Ret == 527) {
			handleStartErr()
		} else {
			uni.showToast({
				title: getApp().globalData.errCodeMsg.RetCodeMsg[result.data.Ret] || result.data.RetMsg,
				icon: "none"
			})
		}
	} else {
		console.log(result.code, 'result.code')
		if ([4100, 4118, 4120, 4121].includes(result.code)) {
			return handleStartErr()
		}
		const errMsg = getApp().globalData.errCodeMsg.CodeMsg[result.code] || result.data.msg;
		uni.showToast({
			title: errMsg,
			icon: 'none',
			duration: 2000,
			success: () => {},
		});
		if (typeof callbackError === 'function') {
			return callbackError(result.code);
		}
	}
}

// 字符串转换UTF8字节 进行16进制转换
export function stringToUTF8Bytes(str) {
	let utf8Bytes = [];
	for (let i = 0; i < str.length; i++) {
		let charCode = str.charCodeAt(i);
		if (charCode < 0x80) {
			utf8Bytes.push(charCode);
		} else if (charCode < 0x800) {
			utf8Bytes.push(0xc0 | (charCode >> 6), 0x80 | (charCode & 0x3f));
		} else if (charCode < 0xd800 || charCode >= 0xe000) {
			utf8Bytes.push(
				0xe0 | (charCode >> 12),
				0x80 | ((charCode >> 6) & 0x3f),
				0x80 | (charCode & 0x3f)
			);
		} else {
			i++; // Surrogate pair
			charCode = 0x10000 + (((charCode & 0x3ff) << 10) | (str.charCodeAt(i) & 0x3ff));
			utf8Bytes.push(
				0xf0 | (charCode >> 18),
				0x80 | ((charCode >> 12) & 0x3f),
				0x80 | ((charCode >> 6) & 0x3f),
				0x80 | (charCode & 0x3f)
			);
		}
	}
	return utf8Bytes.map(byte => byte.toString(16).padStart(2, '0').toUpperCase()).join('');
}

//字符串转字节序列
export function stringToByte(str) {
	let bytes = [];
	let i = 0;
	while (i < str.length) {
		let charCode = str.charCodeAt(i);
		if (charCode < 0x80) {
			bytes.push(charCode);
		} else if (charCode < 0x800) {
			bytes.push(0xc0 | (charCode >> 6));
			bytes.push(0x80 | (charCode & 0x3f));
		} else if (
			(charCode & 0xfc00) === 0xd800 &&
			i + 1 < str.length &&
			(str.charCodeAt(i + 1) & 0xfc00) === 0xdc00
		) {
			// Surrogate pair
			const high = charCode & 0x3ff;
			const low = str.charCodeAt(i + 1) & 0x3ff;
			const codePoint = 0x10000 + (high << 10) + low;
			bytes.push(0xf0 | (codePoint >> 18));
			bytes.push(0x80 | ((codePoint >> 12) & 0x3f));
			bytes.push(0x80 | ((codePoint >> 6) & 0x3f));
			bytes.push(0x80 | (codePoint & 0x3f));
			i++; // Skip low surrogate
		} else {
			bytes.push(0xe0 | (charCode >> 12));
			bytes.push(0x80 | ((charCode >> 6) & 0x3f));
			bytes.push(0x80 | (charCode & 0x3f));
		}
		i++;
	}
	return bytes;
}

// 补位
export function useStrFill(hexStr, count, str, isFront) {
	let hexlength = hexStr.toString().length;
	let n = count - hexlength;
	let strHal = '';
	if (n > 0) {
		for (let i = 0; i < Math.ceil(n / str.length); i++) {
			strHal += str;
		}
		let result = '';
		if (isFront) {
			result = strHal.slice(0, n) + hexStr;
		} else {
			result = hexStr + strHal.slice(0, n);
		}
		return result;
	} else {
		return hexStr;
	}
}

// 字符串转16进制
export function strToHexCharCode(str) {
	if (str === "")
		return "";
	var hexCharCode = [];
	hexCharCode.push("");
	for (var i = 0; i < str.length; i++) {
		hexCharCode.push((str.charCodeAt(i)).toString(16));
	}
	return hexCharCode.join("");
}

export function wakeup(token, sn, callback) {
	let data = {
		sn,
		hostedControl: "1", //是否唤醒主控（空值或0：不唤醒主控；1：唤醒主控）
	}
	getApp().globalData.api.wakeup(data, token, (result) => {
		callback();
	});
}